package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.minio.MinIoClientProperties;
import com.atguigu.lease.web.admin.service.FileService;
import io.minio.*;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {
    @Autowired
    MinioClient minioClient;
    @Autowired
    MinIoClientProperties minIoClientProperties;

    @Override
    public String upload(MultipartFile file) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        String bucketName = minIoClientProperties.getBucketName();
        //获得连接
        boolean b = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        if (!b) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());

            String config = """
                    {
                      "Statement" : [ {
                        "Action" : "s3:GetObject",
                        "Effect" : "Allow",
                        "Principal" : "*",
                        "Resource" : "arn:aws:s3:::%s/*"
                      } ],
                      "Version" : "2012-10-17"
                    }
                    """.formatted(bucketName);
            minioClient.setBucketPolicy(SetBucketPolicyArgs.builder().bucket(bucketName).config(config).build());
        }
        String fileName = UUID.randomUUID() + new SimpleDateFormat("yyyy-MM-dd").format(new Date())
                + "-" + file.getOriginalFilename();
        minioClient.putObject(PutObjectArgs.
                builder().
                object(fileName)
                .bucket(bucketName)
                .stream(file.getInputStream(), file.getSize(), -1)
                .contentType(file.getContentType()).
                build());
       return String.join("/",minIoClientProperties.getEndPoint(),minIoClientProperties.getBucketName(),fileName);
    }
}
